from django.http import JsonResponse
from rest_framework.views import APIView
from apps.user.SMS import send_sms
from apps.user.middleware import MyThrottling
from common.response_code import error_map, RET
from db.models import XlzIncomeDisburseType, XlzIncome
import random
from apps.user.util import token_confirm
from db.models import *
from rest_framework.response import Response
from rest_framework import status
from rest_framework.generics import GenericAPIView, CreateAPIView
from apps.user.userserializers import LoginSerializer, SmsSerializer, MsgSerializer, \
    LogoutSerializer, ClockSerializer, ChangephoneSerializer, ChangeusernameSerializer
from libs.userinfo import daka
from apps.bookkeeping.utils.image_storage import storage


class IndexView(APIView):
    authentication_classes = []

    def get(self, request):
        income = XlzIncome(user_id=1, type_id=1, money=100)
        income.save()

        return JsonResponse({"code": "0", "msg": "access"})


class UserLoginrView(CreateAPIView):
    queryset = XlzUser.objects.all()
    serializer_class = LoginSerializer
    authentication_classes = []

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            phone = serializer.data.get('phone')
            user = XlzUser.objects.filter(phone=phone).first()
            token = token_confirm.generate_validate_token(user.id)
            return Response({'code': status.HTTP_200_OK,
                             'msg': '登录成功',
                             'data': {'user_id': user.id, 'token': token}})
        else:
            print(serializer.errors)
            return Response({'code': 1004, 'msg': '校验参数错误',
                             'data': {'error': serializer.errors, 'token': None}})


class SMSCodeAPIView(GenericAPIView):
    queryset = XlzUser.objects.all()
    serializer_class = SmsSerializer
    authentication_classes = []

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            phone = serializer.data.get('phone')
            vcode = str(random.randint(1000, 9999))
            res = send_sms.delay(phone, vcode)
            if res:
                return Response({'code': 1, 'msg': '发送成功', 'data': {'para': vcode}})
        else:
            return Response({'code': 0, 'msg': '发送失败', 'data': {'info': serializer.errors}})


class MsgViews(GenericAPIView):
    queryset = XlzUser.objects.all()
    serializer_class = MsgSerializer

    def get(self, request):
        try:
            uid = request.user.id
            user = XlzUser.objects.get(pk=uid)
        except Exception as e:
            return Response({
                'code': 107,
                'msg': '该用户不存在',
                'data': {}
            })
        serializer = MsgSerializer(instance=user)
        return Response({
            'code': 200,
            'msg': '查询成功',
            'data': {
                'user_info': serializer.data
            }
        })


class UserLogoutView(GenericAPIView):
    queryset = XlzUser.objects.all()
    serializer_class = LogoutSerializer
    authentication_classes = []

    def post(self, request):
        token = request.headers.get('token')
        if token:
            token_confirm.remove_validate_token(token)
            return Response({
                'code': 200,
                'msg': '退出登录成功'
            })
        else:
            return Response({
                'code': RET.SESSIONERR,
                'msg': error_map[RET.SESSIONERR]
            })


class UserClock(GenericAPIView):
    queryset = XlzClock.objects.all()
    serializer_class = ClockSerializer
    throttle_classes = [MyThrottling]

    def get(self, request):
        uid = request.user.id
        user = XlzUser.objects.get(pk=uid)
        if not user:
            return Response({
                'code': 107,
                'msg': '该用户不存在,请登录',
                'data': {}
            })
        clock_data = XlzUser.objects.filter(id=uid)
        tclock = XlzClock.objects.filter(user_id=uid).first()
        if not tclock:
            tt = XlzClock()
            tt.daka_day = 1
            tt.user_id = uid
            tt.save()
            # 获取打卡天数，记账总天数，记账总笔数
            clock, sum_day, sum_account = daka(queryset=clock_data, uid=uid)
            return Response({
                'code': 200,
                'msg': '查询成功',
                'data': {
                    '连续打卡天数': clock,
                    '记账总天数': sum_day.days,
                    '记账总笔数': sum_account
                }
            })
        else:
            # 打卡次数限制
            nowtime = datetime.now()
            data = XlzClock.objects.filter(user_id=uid).first()
            updatetime = data.update_time
            if (nowtime - updatetime).days < 1:
                return Response({
                    'code': RET.CLOCK_ERROR,
                    'msg': error_map[RET.CLOCK_ERROR],
                    'data': []
                })
            # 获取打卡天数，记账总天数，记账总笔数
            clock, sum_day, sum_account = daka(queryset=clock_data, uid=uid)
            return Response({
                'code': 200,
                'msg': '查询成功',
                'data': {
                    '连续打卡天数': clock,
                    '记账总天数': sum_day.days,
                    '记账总笔数': sum_account
                }
            })


class Changeimage(GenericAPIView):
    queryset = XlzUser.objects.all()
    serializer_class = LogoutSerializer

    def post(self, request):
        try:
            uid = request.user.id
            user = XlzUser.objects.get(pk=uid)
        except Exception as e:
            return Response({
                'code': 107,
                'msg': '该用户不存在,请登录',
                'data': {}
            })
        img_data = request.FILES.get("title_image", None)
        try:
            if img_data is None:
                user.title_image = user.title_image
                user.save()
                return Response({'code': 200, 'msg': '头像没有修改', 'data': user.title_image})
            else:
                img_url = storage(img_data.read())
                user.title_image = img_url
                user.save()
                return Response(
                    {'code': 200, 'msg': '头像保存成功', 'data': {'user_id': uid, 'title_image': user.title_image}})
        except Exception:
            return Response({"code": RET.THIRDERR, "msg": error_map[RET.THIRDERR]})


class Changeusername(GenericAPIView):
    queryset = XlzUser.objects.all()
    serializer_class = ChangeusernameSerializer

    def post(self, request):
        try:
            uid = request.user.id
            user = XlzUser.objects.get(pk=uid)
        except Exception as e:
            return Response({
                'code': 107,
                'msg': '该用户不存在,请登录',
                'data': {}
            })
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            username = serializer.data.get('username')
            user.username = username
            user.save()
            return Response({'code': 200, 'msg': '用户名保存成功', 'data': {'user_id': uid, 'username': user.username}})
        return Response({'code': RET.DATAERR, 'msg': '保存失败', 'data': {'info': serializer.errors}})


class Changephone(GenericAPIView):
    queryset = XlzUser.objects.all()
    serializer_class = ChangephoneSerializer

    def post(self, request):
        try:
            uid = request.user.id
            user = XlzUser.objects.get(pk=uid)
        except Exception as e:
            return Response({
                'code': 107,
                'msg': '该用户不存在,请登录',
                'data': {}
            })
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            phone = serializer.data.get('phone')
            user.phone = phone
            user.save()
            return Response({'code': 200, 'msg': '手机号保存成功', 'data': {'user_id': uid, 'phone': user.phone}})
        return Response({'code': RET.DATAERR, 'msg': '保存失败', 'data': {'info': serializer.errors}})


class Changesex(GenericAPIView):
    queryset = XlzUser.objects.all()
    serializer_class = LogoutSerializer

    def post(self, request):
        try:
            uid = request.user.id
            user = XlzUser.objects.get(pk=uid)
        except Exception as e:
            return Response({
                'code': 107,
                'msg': '该用户不存在,请登录',
                'data': {}
            })
        sex = request.data.get('sex', 0)
        if sex == str(0) or sex == str(1):
            user.sex = sex
            user.save()
            return Response({'code': 200, 'msg': '性别保存成功', 'data': {'user_id': uid, 'sex': user.sex}})
        return Response({
            'code': RET.PARAMERR,
            'msg': error_map[RET.PARAMERR]
        })
